package org.goldenport.g3.app

import org.goldenport.g3._
import org.goldenport.g3.atom._
import org.goldenport.g3.messages._
import org.goldenport.g3.messages.datastore._
import org.goldenport.g3.messages.query._

/**
 * @since   Sep. 25, 2010
 * @version Sep. 25, 2010
 * @author  ASAMI, Tomoharu
 */
class AtomDbCli extends G3Application with UseRecord {
  val kind = 'feed
  val schema = Schema(IdField,
                      'title,
                      ('date, XDate),
                      ('content, XString))
  val url = "http://gihyo.jp/feed/atom"
//  val url = "http://twitter.com/statuses/public_timeline.atom"

  datastore('db, uri="jdbc:derby:target/g3/derbyDB;create=true",
            driver="org.apache.derby.jdbc.EmbeddedDriver",
            username="user1", password="user1")
  service('feed, url)

  agents('init)(MsgSeq(Drop(kind), Create(kind, schema))) invoke("db")

  agents('list)(Query(RecordQuery(AllFieldSlot(kind)))) invoke("db")

  channel('update) invoke("feed") agentc {ctx: G3AgentContext => {
    case AtomFeed(feed) => {
      feed.toRecordSet(entry => {
        Record('id -> entry.id,
               'title -> entry.title,
               'date -> entry.updated,
               'content -> entry.contentText)
      })
    }
  }} invoke("db")

  port("/init") invoke("init")
  port("/list") invoke("list")
  port("/update") invoke("update")
}
